/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sk.lieskove.jianghongtiao.common.utils.text;

import com.cybozu.labs.langdetect.Detector;
import com.cybozu.labs.langdetect.DetectorFactory;
import com.cybozu.labs.langdetect.LangDetectException;
import com.cybozu.labs.langdetect.Language;
import org.apache.log4j.Logger;
import sk.lieskove.jianghongtiao.common.utils.PropertiesUtils;

import java.io.File;
import java.io.Serializable;
import java.util.List;

/**
 * 
 * @author xjuraj e-mail: jjurco.sk_gmail.com
 */
public class LanguageDetection implements Serializable {

    private transient Logger log = Logger.getLogger(LanguageDetection.class);
    private transient PropertiesUtils pu = new PropertiesUtils(LanguageDetection.class);
    private static LanguageDetection languageDetection = null;
    private static final Object syncObj = new Object();

    private LanguageDetection() {
        synchronized (syncObj) {
            File f = new File("./resources/langdetect/profiles/");
            log.debug("Detector factory: profile directory: " + f.getAbsolutePath());
            try {
                DetectorFactory.loadProfile(f);
            } catch (LangDetectException ex) {
                log.error("Cannot load language profile from directory: " + f.getAbsolutePath());
            }
        }
    }

    public static LanguageDetection getInstance() {
        synchronized (syncObj) {
            if (languageDetection == null) {
                languageDetection = new LanguageDetection();
            }
            return languageDetection;
        }
    }

    public String detectLang(String text) {
        synchronized (syncObj) {
            try {
                Detector detector = DetectorFactory.create();
                detector.append(text);
                return detector.detect();
            } catch (LangDetectException ex) {
                log.error("Language detection problem.");
            }
            return null;
        }
    }
    
    public List<Language> detectLangList(String text) {
        synchronized (syncObj) {
            try {
                Detector detector = DetectorFactory.create();
                detector.append(text);
                return detector.getProbabilities();
            } catch (LangDetectException ex) {
                log.error("Language detection problem.");
            }
            return null;
        }
    }
}
